package cn.jiyun.ai.impl;

import cn.jiyun.ai.MessageService;
import cn.jiyun.ai.common.Result;
import cn.jiyun.ai.mapper.DoctorMapper;
import cn.jiyun.ai.mapper.MessageMapper;
import cn.jiyun.ai.pojo.Doctor;
import cn.jiyun.ai.pojo.Message;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    DoctorMapper doctorMapper;

    @Override
    public Result saveMessage(Message message) {
        message.setSendTime(new Date());
        this.updateDoctorCountByMessage(message);
        messageMapper.insert(message);
        return Result.ok(message);
    }

    @Override
    public void updateDoctorCountByMessage(Message message) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Message::getSendId,message.getSendId());
        queryWrapper.lambda().eq(Message::getReceiverId,message.getReceiverId());
        List<Message> list = messageMapper.selectList(queryWrapper);
        if(list.size()==0){
            QueryWrapper<Doctor> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(Doctor::getId,message.getReceiverId());
            Doctor doctor = doctorMapper.selectOne(queryWrapper1);
            doctor.setCount(doctor.getCount()+1);
            doctorMapper.updateById(doctor);
        }
    }
}
